package com.moetube.user.controller;

import com.moetube.entity.Result;
import com.moetube.entity.StatusCode;
import com.moetube.execption.ContinueSignException;
import com.moetube.user.pojo.User;
import com.moetube.user.service.UserService;
import com.moetube.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping
    public Result findAll(){
        try {
            List<User> userList = userService.findAll();
            return new Result(true, StatusCode.OK,"查询成功",userList);
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
    }

    /***
     * 根据ID查询数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findByUserId(@PathVariable String id){
        try {
            User user = userService.findByUserId(id);
            return new Result(true,StatusCode.OK,"查询成功",user);
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"查询失败");
        }

    }

    /**
     * 根据username查询数据
     * @param username
     * @return
     */
    @GetMapping("/load/{username}")
    public Result<User> findByUsername(@PathVariable("username") String username){
        try {
            User user = userService.findByUsername(username);
            return new Result(true,StatusCode.OK,"查询成功",user);
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"查询失败");
        }

    }

    /***
     * 新增数据
     * @param user
     * @return
     */
    @PostMapping
    public Result add(@RequestBody User user){
        try {
            long id = idWorker.nextId();
            user.setId(String.valueOf(id));
            userService.add(user);
            return new Result(true,StatusCode.OK,"添加成功");
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"添加失败");
        }
    }

    /***
     * 修改数据
     * @param user
     * @param id
     * @return
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody User user,@PathVariable String id){
        try {
            user.setUsername(id);
            userService.update(user);
            return new Result(true,StatusCode.OK,"修改成功");
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"修改失败");
        }
    }


    /**
     * 连续签到功能
     * @return
     */
    @PostMapping("/sign")
    public Result ContinueSign() throws ContinueSignException {
        userService.sign();
        return new Result(true,StatusCode.OK,"签到成功");
    }
}
